<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="m-2 w-1/4 xl:w-1/5" style="flex: 1;height: 100%;">
      <DeptTree @select="handleTreeSelected"/>
    </div>
    <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" :searchInfo="searchInfo" style="flex: 1">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleCreate"> 测试tset</a-button>
        <a-button type="primary" @click="handleCreate" v-show="showBtn"> 批量刷新</a-button>
        <a-button preIcon="ant-design:edit-outlined" @click="batchEdit" v-if="!startEdit && showBtn"> 批量编辑</a-button>
        <a-button type="primary" preIcon="ant-design:save-outlined" @click="batchSave" v-if="startEdit && showBtn"> 保存</a-button>
        <a-button preIcon="ant-design:close-outlined" @click="editCancel" v-if="startEdit && showBtn"> 取消</a-button>
      </template>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="getTableAction(record)" />
        </template>
        <template v-if="column.editRow && column.editComponent === 'Switch'">
          <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" :disabled="!startEdit" size="small" v-model:checked="record[column['dataIndex']]" />
          <!-- <span v-else>{{ 'true' == text ? '是' : '否' }}</span> -->
        </template>
        <template v-if="column.editComponent === 'TreeSelect'">
          <a-tree-select v-if="startEdit" v-model:value="record[column['dataIndex'] + 'Name']" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :fieldNames="{ children: 'children', label: 'name', value: 'name', }" allow-clear :tree-data="userData" :load-data="loadUserData" @select="(v, node) => { record[column['dataIndex']] = node.code; }" />
          <span v-else>
            {{ record[column['dataIndex'] + 'Name'] }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'userPosType'">
          <a-select :options="workTypeData" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{ label: 'text', value: 'value', }" />
        </template>
        <template v-if="column.dataIndex === 'personType'">
          <a-select :options="personList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{ label: 'name', value: 'code', }" />
        </template>
        <template v-if="column.dataIndex === 'perfLevelType'">
          <a-select :options="prefLevelList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{ label: 'text', value: 'value', }" />
        </template>
        <template v-if="column.dataIndex === 'prefSalaryType'">
          <a-select :options="prefSalaryList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{ label: 'text', value: 'value', }" />
        </template>
        <template v-if="column.dataIndex === 'prefSalaryWay'">
          <a-select :options="prefSalaryWayList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{ label: 'text', value: 'value', }" />
        </template>
        <template v-if="column.dataIndex === 'displayOrder'">
          <a-input-number style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" size="small" />
          <span v-else>
            {{ text }}
          </span>
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { getDictItemsByCode } from '/@/utils/dict/index';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { PageWrapper } from '/@/components/Page';
import { useModal } from '/@/components/Modal';
import AccountModal from './components/AccountModal.vue';
import DeptTree from './components/DeptTree.vue';

import { columns, searchFormSchema } from './EpmBaseRel.data';
import { list, updateBatch } from './EpmBaseRel.api';
import { useGo } from '/@/hooks/web/usePage';

export default defineComponent({
  name: 'EpmBaseRel',
  components: { BasicTable, PageWrapper, DeptTree, AccountModal, TableAction },
  setup() {
    const showBtn = ref(false); //批量刷新等按钮默认false,左树点击后为true
    let startEdit = ref(false);
    let workTypeData = getDictItemsByCode('epm_work_type');
    let personList = ref([]);
    let prefLevelList = getDictItemsByCode('hub_perf_level_type');
    let prefSalaryList = getDictItemsByCode('hub_pref_salary_type');
    let prefSalaryWayList = getDictItemsByCode('hub_pref_salary_way');
    const go = useGo();
    const [registerModal, { openModal }] = useModal();
    const searchInfo = reactive<Recordable>({});
    const [registerTable, { reload, updateTableDataRecord, getDataSource }] = useTable({
      title: '人员列表',
      api: list,
      rowKey: 'id',
      columns,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      handleSearchInfoFn(info) {
        return info;
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
        title: '操作',
        dataIndex: 'action',
        // slots: { customRender: 'action' },
      },
    });

    function handleCreate() {
      openModal(true, {
        isUpdate: false,
      });
    }

    function handleEdit(record: Recordable) {
      console.log(record);
      openModal(true, {
        record,
        isUpdate: true,
      });
    }

    function batchEdit() {
      let records = getDataSource();
      records.forEach((r) => {
        try {
          r.onEdit(true);
        } catch (e) {
          console.error(e);
        }
      });
      startEdit.value = true;
    }

    function batchSave() {
      let records = getDataSource();
      records.forEach((r) => {
        try {
          r.onEdit(false, true);
        } catch (e) {
          console.log(e);
        }
      });
      setTimeout(() => {
        const data = {
          datas: getDataSource(),
        };
        updateBatch(data).then(() => {
          reload();
        }); //保存数据
        startEdit.value = false;
      }, 500);
    }

    /**
     * 取消编辑
     */
    async function editCancel() {
      let records = getDataSource();
      for (const r of records) {
        try {
          await r.onEdit(false, false);
        } catch (e) { }
      }
      startEdit.value = false;
      reload();
    }

    function handleDelete(record: Recordable) {
      console.log(record);
    }

    function handleSuccess({ isUpdate, values }) {
      if (isUpdate) {
        // 演示不刷新表格直接更新内部数据。
        // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
        const result = updateTableDataRecord(values.id, values);
        console.log(result);
      } else {
        reload();
      }
    }

    // function handleTreeSelected(deptId = '') {
    //   showBtn.value = true;
    //   searchInfo.deptId = deptId;
    //   reload();
    // }

    function handleTreeSelected(orgCode = '') {
      showBtn.value = true;
      searchInfo.orgCode = orgCode;
      reload();
    }

    function handleView(record: Recordable) {
      go('/system/account_detail/' + record.id);
    }

    /**
     * 表格操作栏
     */
    const getTableAction = (record: any) => {
      return [
        {
          icon: 'clarity:info-standard-line',
          tooltip: '查看用户详情',
          onClick: handleView.bind(null, record),
        },
        {
          icon: 'clarity:note-edit-line',
          tooltip: '编辑用户资料',
          onClick: handleEdit.bind(null, record),
        },
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          tooltip: '删除此账号',
          popConfirm: {
            title: '是否确认删除',
            placement: 'left',
            confirm: handleDelete.bind(null, record),
          },
        },
      ]
    }

    return {
      registerTable,
      registerModal,
      handleCreate,
      handleEdit,
      batchEdit,
      batchSave,
      editCancel,
      handleDelete,
      handleSuccess,
      handleTreeSelected,
      handleView,
      searchInfo,
      showBtn,
      startEdit,
      getTableAction,
      workTypeData,
      personList,
      prefLevelList,
      prefSalaryList,
      prefSalaryWayList,
    };
  },
});
</script>